package com.vizend.agilecard;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class AgileCardActivity extends Activity implements View.OnClickListener  {
	
	private ArrayList<Integer> cards;
	private AgileCardAdapter mAdapter;
	
	private ViewPager mPager;
    private ViewGroup mContainer;
    private ImageView mImageView;
    private Button mLeftBtn;
    private Button mBtn;
    private ImageView mCardView;
    private LinearLayout mDotViewer;
    private LinearLayout mCardAllLayout;
    
    private int preItemIndex = -1;
    private int cardItemNum;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        getResourceEventBind();
        
        /** 카드셋팅 */
        initCardSetting();
        
        mAdapter = new AgileCardAdapter();
        mPager = (ViewPager)findViewById(R.id.agileCardViewPager);
        mPager.setAdapter(mAdapter);
        
        /** dotImage display 초기화 */
        initDotImage();
        
        // Prepare the ImageView
        mImageView.setClickable(true);
        mImageView.setFocusable(true);
        mImageView.setOnClickListener(this);

        // Since we are caching large views, we want to keep their cache
        // between each animation
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
        
    }

	private void getResourceEventBind() {
		mDotViewer = (LinearLayout) findViewById(R.id.dotViewer);
        mImageView = (ImageView) findViewById(R.id.back);
        mContainer = (ViewGroup) findViewById(R.id.container);
        mCardAllLayout = (LinearLayout)findViewById(R.id.cardAllLayout);
        mBtn = (Button) findViewById(R.id.rightBtn);
        mBtn.setOnClickListener(mPagerListener);
        mLeftBtn = (Button) findViewById(R.id.leftBtn);
        mLeftBtn.setOnClickListener(mPagerListener);
        
        mCardView = (ImageView)findViewById(R.id.card_half);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_0);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_1);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_2);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_3);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_5);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_8);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_13);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_20);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_40);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.card_100);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.coffee);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.infinity);
		mCardView.setOnClickListener(mCardClickListener);
		mCardView = (ImageView)findViewById(R.id.question);
		mCardView.setOnClickListener(mCardClickListener);
	}

	private void initDotImage() {
		LayoutInflater inflater = (LayoutInflater) mDotViewer.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        for(int i=0; i<cards.size(); i++) {
        	ImageView imageView = (ImageView)inflater.inflate(R.layout.dot_image_view, null);
			mDotViewer.addView(imageView);
        }
        mDotViewer.getChildAt(mPager.getCurrentItem()).setBackgroundResource(R.drawable.btn_banner_on);
	}

	private void initCardSetting() {
		cards = new ArrayList<Integer>();
        cards.add(R.layout.card_0_5);
        cards.add(R.layout.card_0);
        cards.add(R.layout.card_1);
        cards.add(R.layout.card_2);
        cards.add(R.layout.card_3);
        cards.add(R.layout.card_5);
        cards.add(R.layout.card_8);
        cards.add(R.layout.card_13);
        cards.add(R.layout.card_20);
        cards.add(R.layout.card_40);
        cards.add(R.layout.card_100);
        cards.add(R.layout.coffee);
        cards.add(R.layout.infinity);
        cards.add(R.layout.question);
	}
    
    private class AgileCardAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return cards.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((View)object);
			
		}
		
		/**
         * 각 페이지 정의
         */
        @Override
        public Object instantiateItem(View collection, int position) {
        	LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        	
        	View view = inflater.inflate(cards.get(position), null);
        	view.setOnClickListener(mPagerListener);
            ((ViewPager) collection).addView(view, 0);
            
            return view;
        }
        
        @Override
        public void destroyItem(View collection, int position, Object view) {
                ((ViewPager) collection).removeView((View) view);
        }
        
        @Override
        public void finishUpdate(View v) {
        	preItemIndex = mPager.getCurrentItem();
        }
        

        @Override
        public void restoreState(Parcelable pc, ClassLoader cl) {
        }

        @Override
        public Parcelable saveState() {
                return null;
        }

        @Override
        public void startUpdate(View v) {
        	if(preItemIndex != -1)
        		mDotViewer.getChildAt(preItemIndex).setBackgroundResource(R.drawable.btn_banner_off);
        	
        	mDotViewer.getChildAt(mPager.getCurrentItem()).setBackgroundResource(R.drawable.btn_banner_on);
        }
        
        
    }
    
	@Override
	public void onClick(View view) {
		applyRotation(-1, 180, 90);
	}
	
	private View.OnClickListener mCardClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.card_half:
				cardItemNum = 0;
				break;
			case R.id.card_0:
				cardItemNum = 1;
				break;
			case R.id.card_1:
				cardItemNum = 2;
				break;
			case R.id.card_2:
				cardItemNum = 3;
				break;
			case R.id.card_3:
				cardItemNum = 4;
				break;
			case R.id.card_5:
				cardItemNum = 5;
				break;
			case R.id.card_8:
				cardItemNum = 6;
				break;
			case R.id.card_13:
				cardItemNum = 7;
				break;
			case R.id.card_20:
				cardItemNum = 8;
				break;
			case R.id.card_40:
				cardItemNum = 9;
				break;
			case R.id.card_100:
				cardItemNum = 10;
				break;
			case R.id.coffee:
				cardItemNum = 11;
				break;
			case R.id.infinity:
				cardItemNum = 12;
				break;
			case R.id.question:
				cardItemNum = 13;
				break;

			default:
				break;
			}
			mImageView.setVisibility(View.GONE);
            mDotViewer.setVisibility(View.VISIBLE);
            mPager.setVisibility(View.VISIBLE);
            mPager.requestFocus();
			mPager.setCurrentItem(cardItemNum, false);
			mImageView.setImageResource(R.drawable.back);
        	applyRotation(1, 0, 90);
        	mCardAllLayout.setVisibility(View.INVISIBLE);
			mLeftBtn.setText("All");
			
		}
	};
	
	private View.OnClickListener mPagerListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent;
			switch (v.getId()) {
			case R.id.leftBtn:
				if(mCardAllLayout.getVisibility() == View.VISIBLE) {
					mCardAllLayout.setVisibility(View.INVISIBLE);
					mLeftBtn.setText("All");
				} else {
					mCardAllLayout.setVisibility(View.VISIBLE);
					mLeftBtn.setText("Close");
				}
				break;
			case R.id.rightBtn:
				intent = new Intent(v.getContext(), AgileCardHelpActivity.class);
				startActivity(intent);
				break;
			default:
				mImageView.setImageResource(R.drawable.back);
		        applyRotation(1, 0, 90);
				break;
			}
		}
	};
    
    /**
     * Setup a new 3D rotation on the container view.
     *
     * @param position the item that was clicked to show a picture, or -1 to show the list
     * @param start the start angle at which the rotation must begin
     * @param end the end angle of the rotation
     */
    private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(200);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }
    
    /**
     * This class is responsible for swapping the views and start the second
     * half of the animation.
     */
    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
            
            if (mPosition > -1) {
            	mPager.setVisibility(View.GONE);
            	mDotViewer.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();

                rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f, false);
            } else {
                mImageView.setVisibility(View.GONE);
                mDotViewer.setVisibility(View.VISIBLE);
                mPager.setVisibility(View.VISIBLE);
                mPager.requestFocus();

                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
            }

            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }
    
    /**
     * This class listens for the end of the first half of the animation.
     * It then posts a new action that effectively swaps the views when the container
     * is rotated 90 degrees and thus invisible.
     */
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }
}